<template>
  <div class="app-container">
    <el-form
      :model="sortObj"
      :rules="rules"
      ref="sortObj"
      label-width="220px"
      label-position="right"
    >
      <el-form-item label="选择类别：">
        <el-radio-group v-model="sortObj.type" :disabled="isEdit">
          <el-radio :key="1" :label="1">一级类别</el-radio>
          <el-radio :key="2" :label="2">二级类别</el-radio>
          <el-radio :key="3" :label="3">三级类别</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="一级类别：" v-if="sortObj.type == 1" prop="name">
        <el-input v-model="sortObj.name" placeholder="请输入一级类别名称，不超过10个字" style="width: 650px"></el-input>
      </el-form-item>
      <div v-if="sortObj.type == 2 ">
        <el-form-item label="选择一级类别：">
          <el-select v-model="sortObj.parentId" placeholder="请选择一级类别">
            <el-option
              v-for="item in parentOptions"
              :key="item.catId"
              :label="item.name"
              :value="item.catId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级类别：" v-if="sortObj.type == 2" prop="name">
          <el-input v-model="sortObj.name" placeholder="请输入二级类别名称，不超过10个字" style="width: 650px"></el-input>
        </el-form-item>
      </div>

      <div v-if="sortObj.type == 3 ">
        <el-form-item label="选择一级类别：" v-if="sortObj.type == 2 || sortObj.type == 3 ">
          <el-select v-model="parentId" placeholder="请选择一级类别" @change="selectSecond()">
            <el-option
              v-for="item in parentOptions"
              :key="item.catId"
              :label="item.name"
              :value="item.catId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择二级类别：">
          <el-select v-model="sortObj.parentId" placeholder="请选择二级类别">
            <el-option
              v-for="item in childeList"
              :key="item.catId"
              :label="item.name"
              :value="item.catId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="三级类别：" prop="name">
          <el-input v-model="sortObj.name" placeholder="请输入一级类别名称，不超过10个字" style="width: 650px"></el-input>
        </el-form-item>
      </div>

      <el-form-item label="分类排序：" prop="sort">
        <el-input v-model="sortObj.sort" type="number" style="width: 650px"></el-input>
      </el-form-item>

      <el-form-item label="分类图片(宽80*高80)：">
        <div class="clearfix">
          <img
            class="fl margin-r"
            :src="sortObj.avatar"
            @error="setDefultImg"
            width="100"
            height="100"
            alt
          />
          <el-upload
            class="fl"
            ref="avatarUpload"
            name="avatar"
            :action="imageUploadUrl"
            list-type="picture"
            :before-upload="handleBeforeUpload"
            :on-success="handleSuccess"
            :show-file-list="false"
            :auto-upload="true"
            style="width: 420px"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过3m</div>
          </el-upload>
        </div>
      </el-form-item>
    </el-form>
    <el-button type="primary" icon="el-icon-check" @click="submitForm">保存</el-button>
  </div>
</template>

<script>
const validateNumber = (rule, value, callback) => {
  if (value && isNaN(value)) {
    callback("请输入正确的数值");
  } else {
    if (value < 0) {
      callback("请输入正确的数值");
    }
    callback();
  }
};
import {
  getCourseCategory,
  createCourseCategory,
  updateCourseCategory,
  getParentCategories,
  getChildCategories
} from "@/api/courseCategory";
import defultImg from "@/assets/defult270.png";
export default {
  data() {
    return {
      sortObj: {
        type: "",
        avatar: "",
        name: "",
        parentId: "",
        sort: ""
      },
      childeList: [],
      parentId: "",
      rules: {
        name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          { max: 10, message: "最多不超过10个字符", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "分类排序不能为空", trigger: "blur" },
          { validator: validateNumber, trigger: "blur" }
        ]
      },
      imageUploadUrl:
        process.env.BASE_API + "/common/courseCategories/imageUpload",
      parentOptions: []
    };
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    selectSecond() {
      getChildCategories(this.parentId).then(res => {
        this.childeList = res.data.data;
      });
    },
    submitForm() {
      if (this.sortObj.name == "") {
        this.$message({
          title: "提示",
          message: "请填写分类名称!",
          type: "error"
        });
        return;
      }
      if (this.sortObj.sort == "") {
        this.$message({
          title: "提示",
          message: "请填写分类排序!",
          type: "error"
        });
        return;
      }
      if (this.sortObj.type == 2) {
        if (this.sortObj.sort == "") {
          this.$message({
            title: "提示",
            message: "请选择一级分类!",
            type: "error"
          });
          return;
        } else if (this.sortObj.type == 3) {
          if (this.sortObj.sort == "") {
            this.$message({
              title: "提示",
              message: "请选择二级分类!",
              type: "error"
            });
            return;
          }
        }
      }
      if (this.isEdit) {
        this.handleUpdate();
      } else {
        this.handleCreate();
      }
    },
    initOption() {
      getParentCategories()
        .then(res => {
          this.parentOptions.push(...res.data.data);
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleUpdate() {
      const catId = this.$route.params.catId;
      delete this.sortObj.type;
      delete this.sortObj.parentsId;
      updateCourseCategory(catId, this.sortObj)
        .then(res => {
          this.$notify({
            title: "提示",
            message: "提交成功!",
            type: "success"
          });

          // this.close();
          this.$router.go(-1);
        })
        .catch(err => {});
    },
    handleCreate() {
      delete this.sortObj.type;
      createCourseCategory(this.sortObj)
        .then(res => {
          this.$notify({
            title: "提示",
            message: "提交成功!",
            type: "success"
          });

          // this.close();
          this.$router.go(-1);
        })
        .catch(err => {});
    },
    initData() {
      if (this.isEdit) {
        const catId = this.$route.params.catId;
        getCourseCategory(catId)
          .then(res => {
            this.sortObj = res.data.data;

            getParentCategories().then(res => {
              this.parentOptions.push(...res.data.data);

              if (this.sortObj.parentsId) {
                for (let i = 0; i < this.parentOptions.length; i++) {
                  const element = this.parentOptions[i];
                  if (element.catId == this.sortObj.parentsId) {
                    this.parentId = element.name;
                  }
                }
              }
              getChildCategories(this.sortObj.parentsId).then(res => {
                this.childeList = res.data.data;
              });
            });
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    setDefultImg(e) {
      e.target.src = defultImg;
    },
    handleBeforeUpload(file) {
      const isImg =
        file.type == "image/jpeg" ||
        file.type == "image/png" ||
        file.type == "image/gif";
      if (!isImg) {
        this.$message.warning("上传图片只能是 JPG,GIF 或 PNG 格式");
      }
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isLt3M) {
        this.$message.error("上传图片大小不能超过 3MB!");
      }
      return isImg && isLt3M;
    },
    handleSuccess(response, file, fileList) {
      if (response.statusCode == 200) {
        this.sortObj.avatar = response.data.imageUrl;
        this.$message({
          message: "上传成功!",
          type: "info"
        });
      } else {
        this.$message({
          message: "上传失败，请稍候再试!",
          type: "info"
        });
      }
    }
  },
  mounted() {
    if (this.isEdit) {
      this.initData();
    } else {
      this.initOption();
    }
  }
};
</script>

<style scoped>
</style>